visualHUD.editColorRanges = function(element){
	var _data = element.data('HUDItem');
	var _ranges = _data.properties.colorRanges;
	var rangesWindowID = 'editRangesWindow';


	var rangesForm = $('#editRangesForm');
	var rangesFieldset = rangesForm.find('fieldset').eq(0).empty();
	
	var createRangeItem = function(range){
		var HTML = '<div class="f-row">\
						<span class="f-label">%NAME%:</span><span class="f-inputs">\
						<input type="text" name="%NAME%_0" size="12" value="{0}"><input type="text" name="%NAME%_1" size="12" value={1}></span>\
					</div>';
		return HTML.replace(/%NAME%/g, range.name).format(range.range[0], range.range[1]);
	};
	

	$.each(_ranges, function(){
		rangesFieldset.append(createRangeItem(this));
	});
	
	var textboxes = rangesFieldset.find('input[type=text]');
	textboxes.eq(0).attr('readonly', true);
	textboxes.eq(textboxes.length-1).attr('readonly', true);
		
	if(!xpk.Windows[rangesWindowID]){
		rangesForm.submit(function(event){
			var data = $(this).serializeArray();
			console.log(data);
			
			$.each(data, function(){
				for(var a = 0, b = _ranges.length; a < b; a++){
					var ptt = _ranges[a].name + '_';
					var io = this.name.indexOf(ptt);
					if(io > -1){
						var i = this.name.replace(ptt, '');
					};
					_ranges[a].range[i] = this.value;
				};
			});
			
			console.log( element.data('HUDItem'))
			
			xpk.Windows[rangesWindowID].cancel();	   
			return false;
		});
									  
	};
	xpk.General.openModalWindow({
		element: true,
		id: rangesWindowID,
		width: 350,
		html: null,
		title: visualHUD.application.messages.editRangesTitle.format(_data.properties.label.toLowerCase()),
		cancel: function(){
			this.content.find('form').get(0).reset();
			this.content.find('button[type=submit]').attr('disabled', false);
			this.hide();
		}
	});
	
};

visualHUD.application.messages = {
	scriptError: 'There was an error on this page.',
	errorReportSuccess: 'Thanks, mate. Your report has been sent',
	noHUDItems: 'There are no HUD items yet. C\'mon, add some elements first and try again',
	invalidHUDPreset: 'Invalid HUD preset. Aborting...',
	reportErrorTitle: 'Report an application error/bug',
	editRangesTitle: 'Edit {0} color ranges',
	invalidPresetData: 'Application was unable to parse custom HUD data',
	slowPerformanceProperty: 'Depending on your hardware configuration, using {0} may impact your in-game performance and significally lower your FPS.',
	largeImageWarning: 'Image you are trying to import, are too large ({0}). Please, try another image that is less than {1} '
};

visualHUD.application.hints = {
	performanceImpact: function(feature, cookieName){
		var html = '<div class="mb-15">' + visualHUD.application.messages.slowPerformanceProperty.format(feature) + '</div>'+
			'<button type="button" value="OK" class="button-small mr-20" id=""><span>OK</span></button><label class="label-check"><input type="checkbox" /><span>Don\'t show again</span></label>';
		
		var cookie = $.cookie(cookieName);
		if(!cookie) {
			xpk.Messages.warn({
				title: 'Attention',
				message: html
			});
			var messageDIV = xpk.Messages.messenger.wrapper.children().last();
			var check = messageDIV.find('input[type=checkbox]');
			var button = messageDIV.find('button');
			
			button.click(function(){
				if(check.attr('checked')){
					$.cookie(cookieName, true, { expires: 100 });
				};				
				xpk.Messages.messenger.hide(messageDIV);
			});
			$.cookie(cookieName, true, { expires: 1 });
		};
	}
};

visualHUD.loadPreset = function(presetData, callback){
	if(!presetData) {
		throw(visualHUD.application.messages.invalidHUDPreset);
		return false;
	}
	
	var buttons = visualHUD.constructor.buttons;
	for(var a = 0, b = presetData.length; a < b; a++){
		var fn = buttons[presetData[a].name].fn;
		fn.apply(visualHUD.constructor.fn, [presetData[a]])
	};
	if(callback) callback();
};

visualHUD.reportError = function(_reportData){

	var winID = 'errorReportFormWindow';
	
	if(!xpk.Windows[winID]){
		$('#errorReportForm').submit(function(event){
			
			var serial = $(this).serializeArray();
			var text;
			
			if(this.verify && this.verify.value) {				
				xpk.Windows.errorReportFormWindow.cancel();
				return false;
			}
			
			var submitButton = $(this).find('button[type=submit]').attr('disabled', true);
			
			$.each(serial, function(){
				if(this.name == 'comments'){				
				
					if(_reportData.length) {
						this.value += '\n\n---------------\n';
						
						var map = ['Error', 'URL', 'Line'];
						for(var a=0, b = _reportData.length; a<b; a++){
							this.value += map[a] + ': ' + _reportData[a] + "\n";
						};
					};
					
					this.value += '\n\n---------------\n';
					var browserVersion = $.browser.version;
					var browserName = [];
					for(var k in $.browser){
						if(k != 'version') browserName.push(k);
					};
					
					this.value += browserName.join('/') + ' ver.' + browserVersion + "\n";
				}
			});
			
			$.ajax({
				type: 'POST',
				url: this.action,
				data: serial,
				success: function(){
					xpk.Messages.success({
						title: 'Horray ;)',
						message: visualHUD.application.messages.errorReportSuccess 
					});	
					xpk.Windows.errorReportFormWindow.cancel();
					submitButton.attr('disabled', false);
				},
				error: function(_xhr){
					xpk.Messages.error({
						title: 'Ouch ;(',
						message: "Semething went wrong while processing your request. <br />" + _xhr.status + ': ' + _xhr.statusText
					});	
					submitButton.attr('disabled', false);
				}			
			});

			return false;
		});		
	};
	
	xpk.General.openModalWindow({
		element: true,
		id: winID,
		width: 750,
		html: null,
		title: visualHUD.application.messages.reportErrorTitle,
		cancel: function(){
			this.content.find('form').get(0).reset();
			this.content.find('button[type=submit]').attr('disabled', false);
			this.hide();
		}
	});


};

window.onerror = function(errorMsg, url, lineNumber){

	var HTMLTemplate = '<p>{0}</p><ul class="error-details mb-10">{1}</ul><button type="submit" value="Send report" class="button-small" id="sendBugReport"><span>Send report</span></button>';
	var repHTML = '<li><span class="weak">{0}</span>{1}</li>';

	if($(document.body).hasClass(visualHUD.loadingClass) ){
		HTMLTemplate = '<h3>Sorry, mate, but this is critical error ;(</h3><p>It\'s strongly recommended to restart application</p>';
		HTMLTemplate += '<button type="submit" value="Restart application" class="button-small" id="restartAppButton"><span>Restart application</span></button>';
	};
		
	var map = ['Error', 'URL', 'Line'];
	var args = arguments;

	var report = [];
	
	for(var a=0, b = args.length; a<b; a++){
		report.push(repHTML.format(map[a], args[a]));
	};

	var html = 	HTMLTemplate.format(visualHUD.application.messages.scriptError, report.join(''));
	
	xpk.Messages.error({
		title: 'Opps ;(',
		message: html
	});

	xpk.Messages.messenger.wrapper.find('button#sendBugReport').click(function(){		
		visualHUD.reportError(args);
		xpk.Messages.messenger.hide();
		return false;
	});

	xpk.Messages.messenger.wrapper.find('button#restartAppButton').click(function(){		
		$('#restartAppLink').trigger('click');
		return false;
	});	

	
	return false;
};